from newspaper import Article
import os

class Saver:

    def __init__(self):
        self.home_dir = os.path.expanduser('~')
        self.config_dir_path = self.home_dir + "/.config/alice"
        self.files_dir_path = self.config_dir_path + "/files"
        self.articles = list()

        self.create_files_dir()
        self.load_articles()

    def is_files_dir_exists(self):
        return os.path.exists(self.files_dir_path)

    def is_file_exists(self, url: str):
        return os.path.exists(url)

    def create_files_dir(self):
        os.makedirs(self.files_dir_path, exist_ok=True)

    def load_article(self, url: str):
        url = self.files_dir_path + f"/{url}"
        if not self.is_file_exists(url): return None
       
        title, text = "", ""
        with open(url, "r") as file:
            for line in file.readlines():
                if title == "": title = line.replace("\n", "")
                else: text += line 
            file.close()

        article = Article(url=url)
        article.set_title(input_title=title)
        article.set_text(text=text)

        return article
    
    def save_article(self, article: Article, url: str):
        url = self.files_dir_path + f"/{url}"
        if self.is_file_exists(url): return
        
        with open(url, "w") as file:
            file.write(article.title)
            file.write("\n\n")
            file.write(article.text)
            file.close()

    def load_articles(self):
        self.articles.clear()
        for file in os.listdir(self.files_dir_path):
            article = self.load_article(file)
            self.articles.append(article)
        
        return self.articles



if __name__ == "__main__":
    saver = Saver()
    article = saver.load_article("test")
    if article != None:
        print(article.title)
        print("WOOO")
        print(article.text)

